<template>
  <div>
    <div class="img" v-if="accept == 'image/*'">
      <div class="my-img-list-wrapper">
        <div class="my-img-item" :class="{'red' : item.status == 'error'}" v-for="(item, index) in fileList.slice(0, number)"
             :key="index">
          <div class="my-img-item-con">
            <img :src="item.url" alt="">
            <div class="my-img-action">
              <i @click="handlePreview(item)" aria-label="图标: eye-o" class="anticon anticon-eye-o">
                <svg viewBox="64 64 896 896" data-icon="eye" width="1em" height="1em" fill="currentColor"
                     aria-hidden="true" focusable="false" class="">
                  <path
                    d="M942.2 486.2C847.4 286.5 704.1 186 512 186c-192.2 0-335.4 100.5-430.2 300.3a60.3 60.3 0 0 0 0 51.5C176.6 737.5 319.9 838 512 838c192.2 0 335.4-100.5 430.2-300.3 7.7-16.2 7.7-35 0-51.5zM512 766c-161.3 0-279.4-81.8-362.7-254C232.6 339.8 350.7 258 512 258c161.3 0 279.4 81.8 362.7 254C791.5 684.2 673.4 766 512 766zm-4-430c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176zm0 288c-61.9 0-112-50.1-112-112s50.1-112 112-112 112 50.1 112 112-50.1 112-112 112z"></path>
                </svg>
              </i>
              <i v-if="!disabled" @click="handleRemove(item)" aria-label="图标: delete" tabindex="-1" class="anticon anticon-delete"
                 title="删除文件">
                <svg viewBox="64 64 896 896" data-icon="delete" width="1em" height="1em" fill="currentColor"
                     aria-hidden="true" focusable="false" class="">
                  <path
                    d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"></path>
                </svg>
              </i>
            </div>
          </div>
          <div class="move-wrapper" v-if="isMove">
            <a-icon type="backward" theme="filled" @click="handleUp(index)"/>
            <a-icon type="forward" theme="filled" @click="handleDown(index)"/>
          </div>
        </div>
        <a-upload
          name="file"
          listType="picture-card"
          :multiple="number == 1 ? false : isMultiple"
          :action="uploadParams.actionUrl"
          :headers="uploadParams.headers"
          :data="formKeyData"
          :fileList="fileList"
          :beforeUpload="beforeUpload"
          :disabled="disabled"
          :remove="handleRemove"
          :accept="accept"
          @change="handleChange"
          @preview="handlePreview"
          :class="[!isMultiple ? 'imgupload' : '', !isMultiple && picUrl ? 'image-upload-single-over' : '']"
        >
          <div v-if="fileList.length < number">
            <div class="iconp">
              <a-icon :type="uploadLoading ? 'loading' : 'plus'"/>
              <div class="ant-upload-text">{{ text }}</div>
            </div>
          </div>
        </a-upload>
      </div>
    </div>
    <div v-if="accept == 'video/*'">
      <a-upload
        name="file"
      listType="picture-card"
      :multiple="number == 1 ? false : isMultiple"
      :action="uploadParams.actionUrl"
      :headers="uploadParams.headers"
      :data="formKeyData"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      :disabled="disabled"
      :remove="handleRemove"
      :accept="accept"
      @change="handleChange"
      @preview="handlePreview"
      :class="[!isMultiple ? 'imgupload' : '', !isMultiple && picUrl ? 'image-upload-single-over' : '']"
      >
      <div v-if="fileList.length < number">
        <!--<img v-if="!isMultiple && picUrl" :src="getAvatarView()" style="width:100%;height:100%"/>-->
        <div class="iconp">
          <a-icon :type="uploadLoading ? 'loading' : 'plus'"/>
          <div class="ant-upload-text">{{ text }}</div>
        </div>
      </div>
      </a-upload>
    </div>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel()">
      <video width="100%" controls v-if="accept == 'video/*'">
        <source :src="previewImage"  />
      </video>
      <img alt="example" v-else style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>

<script>
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { getFileAccessHttpUrl } from '@/api/manage'
  import { uploadToken } from '@/api/api'
import { includes } from 'lodash'

  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10)
  }
  const getFileName = path => {
    if (path.lastIndexOf('\\') >= 0) {
      let reg = new RegExp('\\\\', 'g')
      path = path.replace(reg, '/')
    }
    return path.substring(path.lastIndexOf('/') + 1)
  }
  export default {
    name: 'JImageUpload',
    data() {
      return {
        uploadLoading: false,
        picUrl: false,
        headers: {},
        fileList: [],
        previewImage: '',
        previewVisible: false,
        token: '',
        formKeyData: {
          token: '',
          key: ''
        },
        uploadHost: this.uploadParams.uploadHost
      }
    },
    props: {
      text: {
        type: String,
        required: false,
        default: '上传'
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: 'temp'
      },
      value: {
        type: [String, Array],
        required: false
      },
      disabled: {
        type: Boolean,
        required: false,
        default: false
      },
      isMultiple: {
        type: Boolean,
        required: false,
        default: false
      },
      //update-begin-author:wangshuai date:20201021 for:LOWCOD-969 新增number属性，用于判断上传数量
      number: {
        type: Number,
        required: false,
        default: 0
      },
      //update-end-author:wangshuai date:20201021 for:LOWCOD-969 新增number属性，用于判断上传数量
      uploadParams: {
        type: Object,
        default: null,
        required: false
      },
      accept: {
        type: String,
        required: false,
        default: 'image/*'
      },
      fileSize: {
        type: Number,
        required: false,
        default: 2
      },
      isMove: {
        type: Boolean,
        default: true
      },
    },
    watch: {
      value: {
        handler(val, oldValue) {
          if (val instanceof Array) {
            this.initFileList(val.join(','))
          } else {
            this.initFileList(val)
          }
          if (!val || val.length == 0) {
            this.picUrl = false
          }
        },
        //立刻执行handler
        immediate: true
      }
    },
    created() {
      // this.fetchUploadToken()
    },
    methods: {
      // 左移
      handleUp(index) {
        if (index === 0) return
        let temp = this.fileList[index - 1]
        this.$set(this.fileList, index - 1, this.fileList[index])
        this.$set(this.fileList, index, temp)

      },

      // 右移
      handleDown(index) {
        if (index === this.fileList.length - 1) return
        let i = this.fileList[index + 1]
        this.$set(this.fileList, index + 1, this.fileList[index])
        this.$set(this.fileList, index, i)
      },

      fetchUploadToken() {
        uploadToken().then(res => {
          if (res.code == 0) {
            this.token = res.data
          } else {
            this.$message.warning(res.msg)
          }
        })
      },
      initFileList(paths) {
        
        if (!paths || paths.length == 0) {
          this.fileList = []
          return
        }
        this.picUrl = true
        let fileList = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          let url;
          if (arr[a].includes('x-oss-process%3Dvideo%2Fsnapshot%2Ct_0%2Cf_jpg%2Cm_fast')) {
            url = getFileAccessHttpUrl(decodeURIComponent(arr[a]))
          } else {
            url = getFileAccessHttpUrl(arr[a])
          }
          fileList.push({
            url: url,
            uid: url,
            name: getFileName(arr[a]),
            status: 'done'
            // uid: uidGenerator(),
            // name: getFileName(arr[a]),
            // status: 'done',
            // url: url,
            // response: {
            //   status: 'history',
            //   message: arr[a]
            // }
          })
        }
        this.fileList = fileList
        this.$emit('fileChange', this.fileList)
        // console.log(this.fileList)
      },
      beforeUpload: function(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
        const isLt2M = file.size / 1024 / 1024 < this.fileSize
        if (!isLt2M) {
          this.$message.error(`图片请小于${this.fileSize}MB!`)
          return new Promise((resolve, reject) => {
            reject()
          })
        }
        if (this.accept == 'image/*') {
          if (!isJpgOrPng) {
            this.$message.error('上传格式有误！')
            return new Promise((resolve, reject) => {
              reject()
            })
          }
        }
        new Promise((resolve, reject) => {
          if (this.accept == 'image/*') {
            if (!isJpgOrPng) {
              this.$message.error('上传格式有误！')
              reject(file)
            }
          }
          if (!isLt2M) {
            this.$message.error(`图片请小于${this.fileSize}MB!`)
            reject(file)
          } else {
            const key = new Date().getTime() + '-' + file.name
            this.formKeyData = {
              // key: key,   // 非必填项，批量上传时不能使用相同key，会导致614报错；不指定key，七牛默认将文件hash作为文件名保存
              token: this.token
            }
            // return isJpgOrPng && isLt2M
            resolve(file)
          }
        })
      },
      // handleChange({ fileList }) {
      //   console.log(fileList, 'fileListfileListfileList')
      //   this.fileList = fileList;
      // },
      handleChange(info) {
        let fileList = []
        if (this.isMultiple) {
          fileList = [...info.fileList]
        } else {
          fileList = info.fileList
        }
        if (fileList.length > this.number && this.isMultiple) {
          this.$message.warning('最多上传' + this.number + '张！')
          return false
          // fileList = fileList.slice(-this.number)
        }


        if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`)
        } else {
          let list = fileList.map(file => {
            if (file.response) {
              file.url = file.response.data
            }
            return file
          })
          this.fileList = list
          // console.log(this.fileList)
          this.$emit('fileChange', this.fileList)
        }
        this.fileList = [...fileList]
      },

      handleRemove(file) {
        const index = this.fileList.indexOf(file)
        const newFileList = this.fileList.slice()
        newFileList.splice(index, 1)
        this.fileList = newFileList
        this.$emit('fileChange', this.fileList)
      },
      // 预览
      handlePreview(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      getAvatarView() {
        if (this.fileList.length > 0) {
          let url = this.fileList[0].url
          return getFileAccessHttpUrl(url)
        }
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = []
        if (!this.isMultiple && uploadFiles.length > 0) {
          arr.push(uploadFiles[uploadFiles.length - 1].response.message)
        } else {
          for (let a = 0; a < uploadFiles.length; a++) {
            // update-begin-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
            if (uploadFiles[a].status === 'done') {
              arr.push(uploadFiles[a].response.message)
            } else {
              return
            }
            // update-end-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
          }
        }
        if (arr.length > 0) {
          path = arr.join(',')
        }
        this.$emit('change', path)
      },
      handleDelete(file) {
        //如有需要新增 删除逻辑
        console.log(file)
      },
      handleCancel() {
        this.previewVisible = false
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>
  .img /deep/ .ant-upload-list {
    display: none;
  }

  .my-img-list-wrapper {
    display: flex;
    flex-wrap: wrap;
  }

  .my-img-list {
    display: flex;
    flex-wrap: wrap;
  }

  .my-img-item {
    position: relative;
    width: 104px;
    height: 104px;
    padding: 8px;
    margin: 0 8px 30px 0;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
  }

  .my-img-item.red {
    border-color: #f5222d;
  }

  .my-img-item-con {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .my-img-item img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .my-img-item i {
    margin: 0 4px;
    cursor: pointer;
  }

  .my-img-item i svg {
    font-size: 16px;
    color: rgba(255, 255, 255, 0.7);
  }

  .my-img-action {
    display: none;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    text-align: center;
    line-height: 102px;
    background: rgba(0, 0, 0, 0.3);
  }

  .my-img-item .my-img-item-con:hover .my-img-action {
    display: block;
  }

  .my-img-item .move-wrapper {
    position: absolute;
    left: 0;
    right: 0;
    bottom: -22px;
    display: flex;
    justify-content: space-between;
    text-align: center;
    font-size: 22px;
  }

  .img /deep/ .ant-upload-picture-card-wrapper {
    width: auto;
  }
</style>
